import time
import random

from flask import Blueprint, render_template, request, redirect, session
# 使用蓝图注册路由
au = Blueprint("author", __name__)
# 导入自定义的数据库工具函数
from utils import downLoadUtil, dbUtil, fetchAuthorUtil
from datetime import datetime

@au.route('/author_list', methods=['GET', 'POST'])
def get_author_list():
    # return "获取作者列表"
    if request.method == 'GET':
        # 查询所有作者信息
        author_info_list = dbUtil.fetch_all_as_dict("select * from author_info", [])
        # print(f"查询结果 author_list结构数据：{author_info_list}")
        return render_template("authorList.html", author_list=author_info_list)
    return None


# 采集关注的up主信息并存入数据库
@au.route('/fetch_author_list', methods=['GET', 'POST'])
def fetch_author_list():
    print(f"拉取up主信息，开始采集关注的up主信息并存入数据库 开始")
    fetchAuthorUtil.fetch_author_list_fun()
    print(f"拉取up主信息，开始采集关注的up主信息并存入数据库 结束")
    return redirect('/author_list')

# 下载单个作者的所有作品
@au.route('/fetch_all_art_by_author_page_url', methods=['GET', 'POST'])
def fetch_all_art_by_author_page_url():
    name = request.args.get('name')
    page_url = request.args.get('page_url')
    # print(f"up_name:{name} up_main_page_url: {page_url}")

    downLoadUtil.download_page(name, page_url)

    # 如果没有抛出异常，更新 MySQL 状态
    update_sql = "UPDATE author_info SET fetch_art_time = %s WHERE up_name = %s"
    update_time = datetime.now()
    dbUtil.execute_update(update_sql, [update_time, name])
    print(f"up_name:{name} up_main_page_url: {page_url} 下载完成，状态已更新")

    print(f"up_name:{name} up_main_page_url: {page_url} 下载完成")

    return redirect("/author_list")


# 下载所有作者的所有作品
@au.route('/download_all_art', methods=['GET', 'POST'])
def download_all_art():

    print("xxx 下载所有作者的所有作品 xxx")

    if request.method == 'GET':
        # 查询所有作者信息
        author_info_list = dbUtil.fetch_all_as_dict("select * from author_info where id", [])
        for author in author_info_list:
            name = author['up_name']
            page_url = author['up_main_page_url']

            print(f"下载所有作者的所有作品 up_name:{name} up_main_page_url: {page_url}")

            downLoadUtil.download_page(name, page_url)
            # 如果没有抛出异常，更新 MySQL 状态
            update_sql = "UPDATE author_info SET fetch_art_time = %s WHERE up_name = %s"
            update_time = datetime.now()
            dbUtil.execute_update(update_sql, [update_time, name])
            print(f"up_name:{name} up_main_page_url: {page_url} 下载完成，状态已更新")

            # 插入随机暂停时间，防止被检测
            pause_time = random.uniform(1, 2)  # 随机暂停 1 到 2 秒
            print(f"暂停 {pause_time:.2f} 秒，防止被检测")
            time.sleep(pause_time)

    return redirect("/author_list")